#!/usr/bin/env python
# Copyright (c) 2011-2012, Universite de Versailles St-Quentin-en-Yvelines
#
# This file is part of ASK.  ASK is free software: you can redistribute
# it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


import os

from common.configuration import Configuration, check_executable
from common.util import fatal


def report(configuration, iteration, labels, new_labels, model, test_set):
    # when iteration is 0 initialize timeseries output file
    ts = configuration("modules.reporter.params.timeseries",
                       expected_type=basestring, default_value="")
    if iteration == 0 and ts:
        tf = open(ts,"w")
        tf.write("samples mean-error max-error rmse mean-relative max-relative\n")
        tf.close()

    # filenames
    prediction = "{0}/prediction{1:05d}.data".format(
        configuration("output_directory"),
        iteration)
    plot = "{0}/plot{1:05d}.png".format(
        configuration("output_directory"),
        iteration)

    # use model to predict test_set
    cmd = [configuration("modules.model.predictor"),
           configuration("configuration_file"),
           model,
           test_set,
           prediction]
    p = os.system(" ".join(cmd))
    if (p != 0):
        fatal("Failure calling model predictor: \n" +
              " ".join(cmd))

    # plot 2D graph
    cmd = [check_executable(configuration("modules.reporter.params.script")),
           configuration("configuration_file"),
           test_set,
           prediction,
           labels,
           new_labels,
           plot]
    p = os.system(" ".join(cmd))
    if (p != 0):
        fatal("Failure calling plotter script: \n" +
              " ".join(cmd))

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description="Interactive reporter")
    parser.add_argument('configuration')
    parser.add_argument('iteration', type=int)
    parser.add_argument('labelled_file')
    parser.add_argument('newly_labelled_file')
    parser.add_argument('model_file')
    args = parser.parse_args()
    C = Configuration(args.configuration)
    report(C,
           args.iteration,
           args.labelled_file,
           args.newly_labelled_file,
           args.model_file,
           C("modules.reporter.params.test_set"))
